package com.yymx.toback.common.sms;

import com.google.gson.Gson;

import com.yymx.toback.common.base.BaseResult;
import com.yymx.toback.common.enums.SmsResultCode;
import com.yymx.toback.common.enums.SmsTypeEnum;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.*;

@Component
public class YunPianSmsSdk {

    private static RedisTemplate<String, Object> redisTemplate;

    private static Logger logger = LoggerFactory.getLogger(com.yymx.toback.common.sms.YunPianSmsSdk.class);
    @Value("${sms.api.key}")
    private String API_KEY;
    //查账户信息的http地址
    private static String URI_GET_USER_INFO =
            "https://sms.yunpian.com/v2/user/get.json";

    //智能匹配模板发送接口的http地址
    private static String URI_SEND_SMS =
            "https://sms.yunpian.com/v2/sms/single_send.json";

    //模板发送接口的http地址
    private static String URI_TPL_SEND_SMS =
            "https://sms.yunpian.com/v2/sms/tpl_single_send.json";

    //发送语音验证码接口的http地址
    private static String URI_SEND_VOICE =
            "https://voice.yunpian.com/v2/voice/send.json";

    //绑定主叫、被叫关系的接口http地址
    private static String URI_SEND_BIND =
            "https://call.yunpian.com/v2/call/bind.json";

    //解绑主叫、被叫关系的接口http地址
    private static String URI_SEND_UNBIND =
            "https://call.yunpian.com/v2/call/unbind.json";

    //编码格式。发送编码格式统一用UTF-8
    private static String ENCODING = "UTF-8";
    private static String RADOM_NUM = "0123456789";

    /**
     * 创建六位的验证码
     *
     * @return
     */
    public static String createIndentifyCode() {

        StringBuffer sb = new StringBuffer(6);
        for (int i = 0; i < 6; i++) {
            char ch = RADOM_NUM.charAt(new Random().nextInt(RADOM_NUM.length()));
            sb.append(ch);
        }
        return sb.toString();
    }
    /**
     * 创建六位的验证码
     *
     * @return
     */
    public static String createIndentifyCode(int num) {
        StringBuffer sb = new StringBuffer(num);
        for (int i = 0; i < num; i++) {
            char ch = RADOM_NUM.charAt(new Random().nextInt(RADOM_NUM.length()));
            sb.append(ch);
        }
        return sb.toString();
    }
    /**
     * 发送短信
     *
     * @param
     * @return
     * @throws Exception
     */
    public BaseResult send(String mobile, String content, String code, SmsTypeEnum type) throws Exception {
        //打印下验证码给测试用
        logger.info("当前发送内容{[]}"+content);
        String result = "";
        switch (type) {

            case NOMAL_MESSAGE:
                result = YunPianSmsSdk.sendSms(API_KEY, content, mobile);
                break;
            case VOICE_MESSAGE:
                result = YunPianSmsSdk.sendVoice(API_KEY, mobile,  code);
                break;
        }
        //对result进行一下解析
        SmsResult jsonResult = new Gson().fromJson(result, SmsResult.class);
        logger.info("运营商返回信息{}",result);
        if (SmsResultCode.SUCCESS.getCode().equals(jsonResult.getCode())) {
            return BaseResult.successMsg(SmsResultCode.SUCCESS.getMessage());
        }else if(SmsResultCode.DUPLICATE.getCode().equals(jsonResult.getCode())){
            //重复提交
            return  BaseResult.failCodeMsg(SmsResultCode.DUPLICATE.getCode(),SmsResultCode.DUPLICATE.getMessage());
        }else if(SmsResultCode.MAXLIMITED_ONE_HOURE.getCode().equals(jsonResult.getCode())){
            return  BaseResult.failCodeMsg(SmsResultCode.MAXLIMITED_ONE_HOURE.getCode(),SmsResultCode.MAXLIMITED_ONE_HOURE.getMessage());
        }else if(SmsResultCode.OVERFLOW_LIMITED.getCode().equals(jsonResult.getCode())){
            return  BaseResult.failCodeMsg(SmsResultCode.OVERFLOW_LIMITED.getCode(),SmsResultCode.OVERFLOW_LIMITED.getMessage());
        }else if(SmsResultCode.UNKNOW_ERROE.getCode().equals(jsonResult.getCode())){
            return  BaseResult.failCodeMsg(SmsResultCode.UNKNOW_ERROE.getCode(),SmsResultCode.UNKNOW_ERROE.getMessage());
        }else if(SmsResultCode.SYSTEM_BUSY.getCode().equals(jsonResult.getCode())){
            return  BaseResult.failCodeMsg(SmsResultCode.SYSTEM_BUSY.getCode(),SmsResultCode.SYSTEM_BUSY.getMessage());
        }else{
            return BaseResult.failMsg("调用云片运营商网关失败");
        }

    }


    /**
     * 取账户信息
     *
     * @return json格式字符串
     * @throws IOException
     */

    public static String getUserInfo(String apikey) throws IOException,
            URISyntaxException {
        Map<String, String> params = new HashMap<String, String>();
        params.put("apikey", apikey);
        return post(URI_GET_USER_INFO, params);
    }

    /**
     * 智能匹配模板接口发短信
     *
     * @param apikey apikey
     * @param text   　短信内容
     * @param mobile 　接受的手机号
     * @return json格式字符串
     * @throws IOException
     */

    public static String sendSms(String apikey, String text,
                                 String mobile) throws IOException {
        Map<String, String> params = new HashMap<String, String>();
        params.put("apikey", apikey);
        params.put("text", text);
        params.put("mobile", mobile);
        return post(URI_SEND_SMS, params);
    }


    /**
     * 通过接口发送语音验证码
     *
     * @param apikey apikey
     * @param mobile 接收的手机号
     * @param code   验证码
     * @return
     */

    public static String sendVoice(String apikey, String mobile, String code) {
        Map<String, String> params = new HashMap<String, String>();
        params.put("apikey", apikey);
        params.put("mobile", mobile);
        params.put("code", code);
        return post(URI_SEND_VOICE, params);
    }


    /**
     * 基于HttpClient 4.3的通用POST方法
     *
     * @param url       提交的URL
     * @param paramsMap 提交<参数，值>Map
     * @return 提交响应
     */

    public static String post(String url, Map<String, String> paramsMap) {
        CloseableHttpClient client = HttpClients.createDefault();
        String responseText = "";
        CloseableHttpResponse response = null;
        try {
            HttpPost method = new HttpPost(url);
            if (paramsMap != null) {
                List<NameValuePair> paramList = new ArrayList<
                        NameValuePair>();
                for (Map.Entry<String, String> param : paramsMap.entrySet()) {
                    NameValuePair pair = new BasicNameValuePair(param.getKey(),
                            param.getValue());
                    paramList.add(pair);
                }
                method.setEntity(new UrlEncodedFormEntity(paramList,
                        ENCODING));
            }
            response = client.execute(method);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                responseText = EntityUtils.toString(entity, ENCODING);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return responseText;
    }



}
